'''
Created on 2012-9-24

@author: infear
'''
import Tkinter;
import time;
from Solve import Solution;
from Model import Boat;

timesleep=1;
unit=25;

class Ui:
    def __init__(self,root):
        self.root=root;
        self.input=Tkinter.Frame(self.root,bd=2);
        self.input.place(x=0,y=0);
        self.canvas=Tkinter.Canvas(self.input,width=400, height=400,bg="white",bd=5);
        self.canvas.place(x=0,y=0);
        self.canvas.pack();
        self.canvas.create_oval(150,150,250,250,fill="red");
        self.output=Tkinter.Frame(self.root, bd=2);
        self.output.place(x=0,y=450);
        self.outputArea=Tkinter.Text(self.output,height=10,width=50);
        self.outputArea.pack(side=Tkinter.LEFT,); 
        self.outputArea.bind("<KeyPress>", lambda e : "break")
          
        self.submit=Tkinter.Button(self.input,width=10,text="Calculate");
        self.submit.place(x=0,y=400);
        self.submit.pack(side=Tkinter.LEFT);
        self.solution=Solution();
        
        self.canvas.bind('<Button-1>',self.click);
        self.submit.bind('<Button-1>',self.getAnswer);
        
      
    
    def click(self,event):
        _length=len(self.solution.boatlist);
        if _length>30:
            self.showinfo("Too much island!")
        elif (150<event.x and event.x<250 and event.y>150 and event.y<250):
            self.showinfo("Position Not valid!");
        else:
            self.outputArea.insert(Tkinter.END, "x:%d\ty:%d\n"%(event.x,event.y));
            self.canvas.create_oval(event.x-5,event.y-5,event.x+5,event.y+5,fill="red");
            self.canvas.create_text(event.x+10,event.y+10,text=_length,fill="blue");
            self.solution.add(Boat(_length,event.x,event.y));
            
    def getAnswer(self,event):
        self.showinfo("InputOver!");
        self.solution.initDistance();
        try:
            _result=self.solution.findShortestPath();
            self.showinfo(str(_result))
            _len=len(_result);
            for i in range(0,_len-1):
                begin,end=self.solution.boatlist[_result[i]],self.solution.boatlist[_result[i+1]];
                self.canvas.create_line(begin.x,begin.y,end.x,end.y);
                time.sleep(timesleep)
        except Exception,e:
            self.showinfo(str(e));

    def showinfo(self,info):
        self.outputArea.insert(Tkinter.END, info+"\n");

win=Tkinter.Tk();
win.title("Fishing Island Problem!")
app=Ui(win);
win.maxsize(420, 600);
win.minsize(420, 600);
win.mainloop();